<template>
  <div class="container-box">
    <el-dialog :title="(dialogForm.id ? '编辑' : '新增') + '客户信息'" :visible.sync="dialogVisible" :show-close="false" :close-on-click-modal="false" width="80%">
      <el-form ref="dialogForm" :model="dialogForm" :rules="rules" inline label-width="80px">
        <template v-for="(column, index) in dialogColums.filter(d => d.isForm)">
          <el-form-item v-if="column.key === 'cat_id'" :key="index" :label="column.title" :prop="column.key">
            <el-select v-model="dialogForm[column.key]" filterable :placeholder="`请选择${column.title}`" style="width: 100%;">
              <el-option v-for="item in goodsCategory" :key="item.cat_id" :label="item.cat_name" :value="item.cat_id" />
            </el-select>
          </el-form-item>
          <el-form-item v-else-if="column.type === 'area'" :key="index" :label="column.title" :prop="column.key">
            <el-select v-model="dialogForm[column.key]" filterable :placeholder="`请选择${column.title}`" style="width: 100%;">
              <el-option v-for="(provice_city, pcIndex) in provice_citys" :key="pcIndex" :label="provice_city" :value="provice_city" />
            </el-select>
          </el-form-item>
          <el-form-item v-else-if="column.type === 'dictDetails'" :key="index" :label="column.title" :prop="column.key">
            <el-select v-model="dialogForm[column.key]" filterable :placeholder="`请选择${column.title}`" style="width: 100%;">
              <el-option v-for="(dict) in dictDetails[column.dictKey] ? dictDetails[column.dictKey].data : []" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item v-else-if="column.type === 'textarea'" :key="index" :label="column.title" :prop="column.key" class="textarea-form-item">
            <el-input v-model="dialogForm[column.key]" :type="column.type" :placeholder="`请输入${column.title}`" />
          </el-form-item>
          <el-form-item v-else :key="index" :label="column.title" :prop="column.key">
            <el-input v-if="column.type === 'number'" v-model.number="dialogForm[column.key]" :type="column.type" :placeholder="`请输入${column.title}`" clearable />
            <el-input v-else v-model="dialogForm[column.key]" :type="column.type" :placeholder="`请输入${column.title}`" clearable />
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="saving" @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="saving" @click="onDialogConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import { goodsIndex } from '../../api/goods';
import { customerDetail, customerAdd, customerUpdate } from '../../api/customer';
import curde from '@/mixins/curde'

export default {
  name: 'CustomerEdit',
  mixins: [curde],
  // props: {
  //   id: {
  //     type: String,
  //     default: ''
  //   },
  //   operateType: {
  //     type: String,
  //     default: ''
  //   }
  // },
  data() {
    return {
      dialogColums: [
        { title: '单位名称', key: 'company_name', type: 'text', isFilter: true, isTable: true, isForm: true },
        { title: '联系人', key: 'customer_name', type: 'text', isFilter: true, isTable: true, isForm: true },
        { title: '电话', key: 'phone', type: 'text', isFilter: true, isTable: true, isForm: true },
        { title: '固定电话', key: 'tel_phone', type: 'text', isFilter: true, isTable: true, isForm: true },
        { title: '区域', key: 'area', type: 'area', isFilter: true, isTable: true, isForm: true },
        { title: '详情地址', key: 'area_address', type: 'textarea', isFilter: true, isTable: true, isForm: true },
        { title: '企业类型', key: 'company_type', type: 'dictDetails', dictKey: 'company_type', isFilter: true, isTable: true, isForm: true },
        { title: '供销类型', key: 'customer_type', type: 'dictDetails', dictKey: 'customer_type', isFilter: true, isTable: true, isForm: true },
        { title: '开户行', key: 'bank_name', type: 'text', isFilter: true, isTable: true, isForm: true },
        { title: '银行帐号', key: 'bank', type: 'text', isFilter: true, isTable: true, isForm: true },
        { title: '状态', key: 'status', type: 'text', isFilter: true, isTable: true, isForm: false },
        { title: '备注', key: 'remarks', type: 'textarea', isFilter: true, isTable: true, isForm: true }
      ],
      list: [],
      saving: false,
      dialogVisible: false,
      rules: {
        company_name: [
          { required: true, message: '请输入单位名称', trigger: ['change', 'blur'] }
          // { required: true, message: '分类名称已存在', validator: cateNameValidator }
        ],
        full_goods_name: [
          { required: true, message: '请输入商品全称', trigger: ['change', 'blur'] }
          // { required: true, message: '分类名称已存在', validator: cateNameValidator }
        ],
        // customer_name: [{ required: true, message: '请输入联系人', trigger: ['change', 'blur'] }],
        area: [{ required: true, message: '请选择区域', trigger: ['change', 'blur'] }],
        // company_type: [{ required: true, message: '请选择企业类型', trigger: ['change', 'blur'] }]
        customer_type: [{ required: true, message: '请选择供销类型', trigger: ['change', 'blur'] }]
      },
      // dialogForm: {
      //   area: '广东省 广州市',
      //   area_address: '天健广场',
      //   bank: '123123',
      //   bank_name: '中国银行',
      //   company_name: '单位全称',
      //   full_company_name: '单位简称',
      //   company_type: '1',
      //   customer_name: '林',
      //   customer_type: '1',
      //   phone: '13812312312',
      //   remarks: '备注',
      //   status: '1',
      //   tel_phone: '020123123'
      // },
      dialogForm: {
        area: '',
        area_address: '',
        bank: '',
        bank_name: '',
        company_name: '',
        full_company_name: '',
        company_type: '',
        customer_name: '',
        customer_type: '2',
        phone: '',
        remarks: '',
        status: '1',
        tel_phone: ''
      },
      operateType: '',
      id: ''
    };
  },
  watch: {
    id(val) {
      if (val) {
        this.getDetail(val);
      }
    }
  },
  created() {
    // this.getData();
    console.log('customer--add==', this.dictDetails);
  },
  methods: {
    showDialog(operateType, params) {
      console.log('showDialog==', operateType, params, this.id);
      this.operateType = operateType;
      this.id = params?.id || '';
      // this.dialogForm = 
      if (operateType === 'edit' && params && params?.id) {
        this.getDetail(params.id);
      }
      this.dialogVisible = true;
    },
    closeDialog() {
      this.dialogVisible = false;
    },
    async getDetail(id) {
      console.log('getDetail==', id);
      const { data, code } = await customerDetail({ id: id || this.id });
      this.dialogForm = { ...data };
    },
    // dialog 提交；
    async onDialogConfirm() {
      let isValid = false;
      console.log('onDialogConfirm--this.$refs.dialogForm.==', this.$refs.dialogForm);
      this.$refs.dialogForm.validate(valid => {
        console.log('onDialogConfirm--valid==', valid);
        isValid = valid;
      })
      console.log('onDialogConfirm--this.saving ==', this.saving, isValid);
      if (this.saving) return this.$message.error('请勿重复提交');
      if (!isValid) return;
      // this.$message.error('请检查提交内容');

      this.saving = true;
      try {
        const payload = this.$json.cloneDeep(this.dialogForm);
        payload.full_company_name = payload.company_name;
        let res;
        if (this.operateType === 'add') {
          res = await customerAdd(payload);
        }
        else if (this.operateType === 'edit' && this.id) {
          res = await customerUpdate(payload);
        }
        console.log('onDialogConfirm--res==', res);
        if (res.data) {
          if (res.data?.code < 0) {
            this.$message({ message: res.data?.msg || '操作失败', type: 'error' })
          }
          else {
            this.closeDialog();
            this.$message({ message: '操作成功', type: 'success' })
            this.$emit('callback', true, res.data);
          }
        }
        else {
          this.$message({ message: res?.msg || '操作失败', type: 'error' })
        }

        // this.$emit(true, { ...res });
        // if (data && data.length === 2) {
        //   if (data[1]) {
        //     this.getData();
        //     this.$message.success('添加成功')
        //     this.dialogVisible = false;
        //   }
        //   else {
        //     this.$message.error(`添加失败: ${payload.goods_name} ${payload.full_goods_name} 已存在`)
        //   }
        // }
        // else {
        //   this.$message.error(`异常：添加失败`)
        // }
      }
      catch (e) {
        console.log('customerAdd--e==', e);
      }
      this.saving = false;
    },
    handleRowResult(item, row) {
      // console.log('handleRowResult--item', item, row);
      if (item.key === 'stock') {
        if (row.stock && row.unit_name2 && row.unit_convert !== row.unit_convert2) {
          const unitNum = row.stock % row.unit_convert2;
          const unitNum2 = Math.floor(row.stock / row.unit_convert2);
          return `${unitNum2}${row.unit_name2}${unitNum}${row.unit_name}`
        }
        return `${row.stock}${row.unit_name}`
      }
      return row[item.key] || '';
    }
  }
}

</script>
<style lang="scss" scoped>
.container-box {
  padding: 20px;
}

.table-box {
  // padding: 20px;
}
</style>
